import axios from 'axios';
import env from '../config/env';
import store from '../vuex/store';
import crypto from 'crypto';
import {formatTime} from'./time'
let qs = require('qs');

let util = {

};
util.title = function (title) {
    window.document.title = title;
};


util.md5s = function(str){
    var md5 = crypto.createHash('md5');  
    md5.update(str);  
    str = md5.digest('hex');
    return str; 
}

const ajaxUrl = BASE_URL
util.ajax = axios.create({
    baseURL: ajaxUrl,
    timeout: 60000,
});
// request拦截器
util.ajax.interceptors.request.use(config => {
    // Do something before request is sent
    // if (sessionStorage.getItem('id')) {
    //     config.headers['X-Token'] = sessionStorage.getItem('token'); // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
    // }
    
    config.headers['Token'] = sessionStorage.getItem('token')?sessionStorage.getItem('token'):''; // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
    config.headers['Yid'] = sessionStorage.getItem('id')?sessionStorage.getItem('id'):'';

    if(config.url){
        let _url = config.url.split("/")
        //console.log(_url)
        let str = "kuaibao"+_url[3]+_url[4]+_url[5]+"yun"
        //console.log(str)
        config.headers['Key'] = util.md5s(str)
    }
    //console.log(config)
    return config;
}, error => {
    // Do something with request error
    Promise.reject(error);
})

util.ajax.interceptors.response.use(
    response => {
        const res = response.data;
        if (res.err == 301) {
            sessionStorage.removeItem('id');
            sessionStorage.removeItem('token');
            location.reload();
            return Promise.reject(error);
        } else {
            return response;
        }
    },
    error => {
        return Promise.reject(error);
    }
)

util.inOf = function (arr, targetArr) {
    let res = true;
    arr.map(item => {
        if (targetArr.indexOf(item) < 0) {
            res = false;
        }
    });
    return res;
};

util.oneOf = function (ele, targetArr) {
    if (targetArr.indexOf(ele) >= 0) {
        return true;
    } else {
        return false;
    }
};



util.openNewPage = function (vm, name, argu, query) {
    let pageOpenedList = vm.$store.state.pageOpenedList;
    let openedPageLen = pageOpenedList.length;
    let i = 0;
    let tagHasOpened = false;
    while (i < openedPageLen) {
        if (name === pageOpenedList[i].name) { // 页面已经打开
            vm.$store.commit('pageOpenedList', {
                index: i,
                argu: argu,
                query: query
            });
            tagHasOpened = true;
            break;
        }
        i++;
    }
    if (!tagHasOpened) {
        let tag = vm.$store.state.tagsList.filter((item) => {
            if (item.children) {
                return name === item.children[0].name;
            } else {
                return name === item.name;
            }
        });
        tag = tag[0];
        if (tag) {
            tag = tag.children ? tag.children[0] : tag;
            if (argu) {
                tag.argu = argu;
            }
            if (query) {
                tag.query = query;
            }
            vm.$store.commit('increateTag', tag);
        }
    }
    vm.$store.commit('setCurrentPageName', name);
};

util.toDefaultPage = function (routers, name, route, next) {
    let len = routers.length;
    let i = 0;
    let notHandle = true;
    while (i < len) {
        if (routers[i].name === name && routers[i].children && routers[i].redirect === undefined) {
            route.replace({
                name: routers[i].children[0].name
            });
            notHandle = false;
            next();
            break;
        }
        i++;
    }
    if (notHandle) {
        next();
    }
};

//----------------------------------------------------------
//    功能：根据身份证号获得出生日期
//  参数：身份证号 psidno
//    返回值：
//    出生日期
//----------------------------------------------------------
util.GetBirthday = function(psidno){
            var birthdayno,birthdaytemp
            if(psidno.length==18){
                birthdayno=psidno.substring(6,14)
            }else if(psidno.length==15){
                birthdaytemp=psidno.substring(6,12)
                birthdayno="19"+birthdaytemp
            }else{
                
                return false
            }
            var birthday=birthdayno.substring(0,4)+"-"+birthdayno.substring(4,6)+"-"+birthdayno.substring(6,8)
            return birthday    
}
//----------------------------------------------------------
//    功能：根据身份证号获得性别
//  参数：身份证号 psidno
//    返回值：
//    性别
//----------------------------------------------------------
util.Getsex=function(psidno){
            var sexno,sex
            if(psidno.length==18){
                sexno=psidno.substring(16,17)
            }else if(psidno.length==15){
                sexno=psidno.substring(14,15)
            }else{
                
                return false
            }
            var tempid=sexno%2;
            if(tempid==0){
                sex=2
            }else{
                sex=1
            }
            return sex
}

util.getAstro = function(m,d){
    let constellation = "魔羯水瓶双鱼牡羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯".substr(m*2-(d<"102223444433".charAt(m-1)- -19)*2,2);
    return (constellation+'座')
  }



//操作权限转换
util.actions2Object = function(_array){
    let _obj = {}
    if(_array.length > 0){    
        for(var i=0,len =_array.length;i<len;i++){
            _obj[_array[i]] = true
        }
    }
    return _obj
}

//路由转换  
let transformToArray = function(obj){
    var router_arry = []
    var toogle_arry = []
   // console.log(Object.keys(obj))
    var _arry = Object.keys(obj)
    if(_arry.length > 0){
        for(var i =0;i<_arry.length;i++){
            //console.log(Object.keys(obj[_arry[i]]))
            let _sarry = obj[_arry[i]]
            toogle_arry.push(_arry[i])
            if(_sarry.length > 0){
                for(var k = 0;k<_sarry.length;k++){
                    router_arry.push(_arry[i]+'/'+_sarry[k])
                    toogle_arry.push(_sarry[k])
                }
            }
        }
    //    console.log(router_arry)
    //    console.log(toogle_arry)
    }
    let _obj = {
        router_arry:router_arry,
        toogle_arry:toogle_arry
    }

    return _obj

}
let newRouter = function(st,router){
    let toggle_array = []
    let st_array = st.split("/")
    if(st_array.length > 1){
        //console.log(st_array[0])
       // console.log(st_array[1])
        //console.log(router)
        
        if(router[st_array[0]]){
            return  router[st_array[0]][st_array[1]]
        }
        
    }else{
        return  router[st_array[0]]
    }
}

let getSideKey = function(){
    let st_array = st.split("/")
    if(st_array.length > 1){
        //console.log(st_array[0])
        //console.log(st_array[1])
        //console.log(router)
        //console.log(router[st_array[0]][st_array[1]])
        if(router[st_array[0]]){
            return  router[st_array[0]][st_array[1]]
        }
        
    }else{
        return  router[st_array[0]]
    }
}

util.transformRouter = function(router,operation){
    let _obj = transformToArray(operation)
    let roter_arry = _obj.router_arry
    let toogle_arry = _obj.toogle_arry
    var newLink = []
    //console.log(router)
    //console.log(roter_arry)
    let roter_arry_length = roter_arry.length
    if( roter_arry_length > 0){
        for(var i =0;i<roter_arry_length;i++){
            let newobj = newRouter(roter_arry[i],router)
            if(newobj){
                newLink.push(newRouter(roter_arry[i],router))
            }
            
        }
    }
    let toogle_obj = {}
    let toogle_arry_length = toogle_arry.length
    if(toogle_arry_length > 0){
        for(var j=0;j<toogle_arry_length;j++){
            toogle_obj[toogle_arry[j]] = true
        }
    }
    store.dispatch('getSideList',toogle_obj)
    return newLink
}


export default util;